package com.tiankun.eurekauserinfo.controller;

import com.tiankun.eurekauserinfo.exception.BusinessException;
import com.tiankun.eurekauserinfo.pojo.Order;
import com.tiankun.eurekauserinfo.pojo.OrderGoods;
import com.tiankun.eurekauserinfo.proxy.GoodsHandler;
import com.tiankun.eurekauserinfo.proxy.TicketHandler;
import com.tiankun.eurekauserinfo.service.OrderService;
import com.tiankun.eurekauserinfo.utils.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * Created with IntelliJ IDEA
 * User: bear
 * Date: 2020/11/13
 * Description
 * Version: V1.0
 */
@RestController
@RequestMapping("order")
@CrossOrigin   //用于实现跨域的注解
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    GoodsHandler goodsHandler;
    @Resource
    private TicketHandler ticketHandler;


    @PostMapping(value = "addOrder", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map addOrder(@RequestBody Map<String, Object> map) {
        JsonResult jsonResult = new JsonResult();
        //添加订单
        String orderRandom = orderService.addOrder((String) map.get("userPhone"), (List<Map<String, Object>>) map.get("godDetails"));

        //通过订单号查询订单详情
        Order order = orderService.findByOrderId(orderRandom);
        if (order == null) {
            throw new BusinessException("订单不存在，请稍后再试");
        }
        //设置规定的传参格式(夸模块通信获取商品详细信息)
        Map<String, Integer> goodsDetail = new HashMap<>();
        //定义一个list集合，用来存放订单的所有信息
        List<Map<String, Object>> list = new ArrayList<>();
        //给map一个商品的id 先获取到订单中的详情信息
        List<OrderGoods> goods = order.getGoods();
        for (OrderGoods orderGoods : goods) {
            //按规定传参夸模块获取商品信息
            //1.取的循环遍历商品取得商品id
            goodsDetail.put("godId", orderGoods.getGoodsId());
            //2.得到商品详情接口返回的数据
            Object data = goodsHandler.goodsDetails(goodsDetail).get("data");
            //用一个零时的map用来存放商品的详情信息
            Map<String, Object> goodsData = new HashMap<>();
            //3.得到商品详细信息
            goodsData.put(String.valueOf(orderGoods.getId()), data);
            list.add(goodsData);
        }
        //获取到商品的详情
        //用一个map来存放订单详情，其中内容包括订单，以及商品详细信息
        Map<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("order", order);
        //整个订单的所有商品的所有信息
        orderDetail.put("goodsDetail", list);
        jsonResult.setData(orderDetail);
        jsonResult.setMsg("订单创建成功,订单信息");
        jsonResult.setCode("200");

        return jsonResult.getValues();
    }

    /**
     * 支付接口
     *
     * @param map ticketId，userPhone，orderRandom
     * @return
     */

    @RequestMapping(value = "payment", produces = MediaType.APPLICATION_JSON_VALUE)
    public String payment(@RequestBody Map<String, Object> map) {
        //1.通信获取优惠券详情
        //判断优惠券id是否为空
        Integer ticketId = (Integer) map.get("ticketId");
        //定义一个优惠额度 初始值为0
        Integer tktMoney = 0;
        if (ticketId != null) {
            //2.得到优惠券减的额度
            Map<String, Object> ticket = (Map) ticketHandler.getTicket((Integer) map.get("ticketId")).get("data");
            tktMoney = (Integer) ticket.get("money");
        }
        //3.传入所减金额
        String payment = orderService.payment((String) map.get("userPhone"), tktMoney, (String) map.get("orderRandom"), ticketId);
        return payment;
    }

    /**
     * 通过订单号查询订单详情
     *
     * @param map orderRandom
     * @return 返回查询结果
     */
    @PostMapping(value = "findOrder", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map findOrder(@RequestBody Map<String, String> map) {
        JsonResult jsonResult = new JsonResult();
        //通过订单号查询订单详情
        Order order = orderService.findByOrderId(map.get("orderRandom"));
        if (order == null) {
            throw new BusinessException("订单不存在，请稍后再试");
        }
        //设置规定的传参格式(夸模块通信获取商品详细信息)
        Map<String, Integer> goodsDetail = new HashMap<>();
        //定义一个list集合，用来存放订单的所有信息
        List<Map<String, Object>> list = new ArrayList<>();
        //给map一个商品的id 先获取到订单中的详情信息
        List<OrderGoods> goods = order.getGoods();
        for (OrderGoods orderGoods : goods) {
            //按规定传参夸模块获取商品信息
            //1.取的循环遍历商品取得商品id
            goodsDetail.put("godId", orderGoods.getGoodsId());
            //2.得到商品详情接口返回的数据
            Object data = goodsHandler.goodsDetails(goodsDetail).get("data");
            //用一个零时的map用来存放商品的详情信息
            Map<String, Object> goodsData = new HashMap<>();
            //3.得到商品详细信息
            goodsData.put(String.valueOf(orderGoods.getId()), data);
            list.add(goodsData);
        }
        //获取到商品的详情
        //用一个map来存放订单详情，其中内容包括订单，以及商品详细信息
        Map<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("order", order);
        //整个订单的所有商品的所有信息
        orderDetail.put("goodsDetail", list);
        jsonResult.setData(orderDetail);
        jsonResult.setCode("200");
        jsonResult.setMsg("订单详情");
        return jsonResult.getValues();
    }

    /**
     * 通过号码查询所有的订单
     *
     * @param map userPhone
     * @return 返回查询结果
     */
    @PostMapping(value = "findByUserPhone", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map findByUserPhone(@RequestBody Map<String, String> map) {
        JsonResult jsonResult = new JsonResult();
        List<Order> orderList = orderService.findByUserPhone(map.get("userPhone"));
        jsonResult.setCode("200");
        jsonResult.setMsg("所有订单");
        jsonResult.setData(orderList);
        return jsonResult.getValues();
    }

    @RequestMapping(value = "alipayNotify", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map alipayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> map = orderService.alipayNotify(request, response);
        if (map != null) {
            ticketHandler.update((Integer) map.get("tktId"), (String) map.get("userPhone"), 1);
        }
        jsonResult.setCode("200");
        jsonResult.setMsg("待发货");
        return jsonResult.getValues();
    }

    @RequestMapping(value = "rush", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map rush(@RequestBody Map<String, Object> map) {
        JsonResult jsonResult = new JsonResult();
        //需要抢购活动的id，抢购商品的id，抢购的价格，抢购这的电话号码userPhone

        RedisTemplate redisTemplate = new RedisTemplate();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //获取用户的电话号码
        String userPhone = (String) map.get("userPhone");
        Integer spkId = (Integer) map.get("spkId");

        Boolean lock = valueOperations.setIfAbsent("lock", userPhone, 30, TimeUnit.SECONDS);
        if (lock) {
            //如果用户抢到锁支援
            //判断库存是否足够
            Integer stock = (Integer) valueOperations.get("stock" + spkId);
            if (stock > 0) {
                //如果库存大于0，进行下单操作
                //设置一个list来装秒杀商品的基本信息
                List<Map<String, Object>> list = new ArrayList<>();
                Map<String, Object> goodsDetail = new HashMap<>();
                //活动价格
                goodsDetail.put("money", (Integer) map.get("money"));
                //抢购数量，默认为1
                goodsDetail.put("godNumber", 1);
                //抢购商品的id
                goodsDetail.put("godId", (Integer) map.get("godId"));
                list.add(goodsDetail);
                //生成订单
                //判断当前锁是否本人操作
                if (userPhone.equals(valueOperations.get("lock"))) {
                    //如果是，创建订单
                    String orderRandom = orderService.addOrder(userPhone, list);

                    //通过订单号查询订单详情
                    Order order = orderService.findByOrderId(orderRandom);
                    if (order == null) {
                        throw new BusinessException("订单不存在，请稍后再试");
                    }
                    //设置规定的传参格式(夸模块通信获取商品详细信息)
                    Map<String, Integer> fGoodsDetail = new HashMap<>();
                    //定义一个list集合，用来存放订单的所有信息
                    List<Map<String, Object>> fList = new ArrayList<>();
                    //给map一个商品的id 先获取到订单中的详情信息
                    List<OrderGoods> goods = order.getGoods();
                    for (OrderGoods orderGoods : goods) {
                        //按规定传参夸模块获取商品信息
                        //1.取的循环遍历商品取得商品id
                        fGoodsDetail.put("godId", orderGoods.getGoodsId());
                        //2.得到商品详情接口返回的数据
                        Object data = goodsHandler.goodsDetails(fGoodsDetail).get("data");
                        //用一个零时的map用来存放商品的详情信息
                        Map<String, Object> goodsData = new HashMap<>();
                        //3.得到商品详细信息
                        goodsData.put(String.valueOf(orderGoods.getId()), data);
                        fList.add(goodsData);
                    }
                    //获取到商品的详情
                    //用一个map来存放订单详情，其中内容包括订单，以及商品详细信息
                    Map<String, Object> orderDetail = new HashMap<>();
                    orderDetail.put("order", order);
                    //整个订单的所有商品的所有信息
                    orderDetail.put("goodsDetail", fList);
                    //创建订单成功，秒杀库存-1
                    valueOperations.set("stock" + spkId, --stock);
                    //完成操作，释放资源
                    redisTemplate.delete("lock");
                    jsonResult.setData(orderDetail);
                    jsonResult.setCode("200");
                    jsonResult.setMsg("抢购成功");
                    return jsonResult.getValues();
                }
            }
        }
        jsonResult.setMsg("抢购失败");
        jsonResult.setCode("500");
        return jsonResult.getValues();
    }

    @PostMapping(value = "confirm", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map confirm(@RequestParam("orderId") Integer orderId) {
        JsonResult jsonResult = new JsonResult();
        Integer integer = orderService.confirmReceipt(orderId);
        if (integer != 1) {
            throw new BusinessException("确认收货失败，请稍后再试");
        }
        jsonResult.setCode("200");
        jsonResult.setMsg("确认收货");
        return jsonResult.getValues();
    }
}
